<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="装备名称">
            <MedicineInfo :value="{ mc: formState?.equipmentName, gg: formState?.specifications, cj: formState?.manufacturer }" />
          </a-descriptions-item>
          <a-descriptions-item label="供应商">{{ formState?.supplierName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="资产分类"> {{ formState?.classificationName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="数量"> {{ formState?.qty || '-' }}</a-descriptions-item>
          <a-descriptions-item label="品牌">{{ formState?.brand || '-' }}</a-descriptions-item>
          <a-descriptions-item label="型号"> {{ formState?.model || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单人"> {{ formState?.createUser || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单时间"> {{ formState?.createTime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable
        :data-source="dataSource"
        column-code="000585"
        :loading="loading"
        max-fill
        :extra-height="64"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'NO'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'equipmentNumber'">
            <EditCell title="设备序列号">
              <BaseInput v-model:value="record.equipmentNumber" @blur="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'sourceName'">
            <EditCell title="装备来源">
              <SelectItem
                v-model:value="record.sourceName"
                type="DT00291"
                placeholder="请选择"
                @change="
                  (event) => {
                    record.sourceCode = event
                    editRow(record)
                  }
                "
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'startDate'">
            <EditCell title="启用日期">
              <a-date-picker v-model:value="record.startDate" value-format="YYYY-MM-DD" @change="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'deptName'">
            <EditCell title="配发科室">
              <SelectSection
                v-model:value="record.deptName"
                :search-params="{ yxzt: 0 }"
                class="h-full allot"
                placeholder="请输入"
                @change="
                  (event) => {
                    record.deptCode = event
                    editRow(record)
                  }
                "
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'userEmpName'">
            <EditCell title="使用人">
              <SelectTable
                v-model:value="record.userEmpName"
                type="员工"
                @select="
                  (event) => {
                    record.userEmpName = event.empName
                    record.userEmpId = event.empId
                    editRow(record)
                  }
                "
              />
            </EditCell>
          </template>

          <template v-if="column.dataIndex === 'configAddr'">
            <EditCell title="配置地点">
              <BaseInput v-model:value="record.configAddr" @blur="editRow(record)" />
            </EditCell>
          </template>

          <template v-if="column.dataIndex === 'expectedLimit'">
            <EditCell title="使用年限">
              <BaseInput v-model:value="record.expectedLimit" v-input:int v-input-selection placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>

          <template v-if="column.dataIndex === 'action'">
            <BaseButton confirm-text="确认删除？" type="text" danger size="small" @click="onDelete(record)">删除</BaseButton>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button v-if="formState?.qty > dataSource.length" class="mr-2" :disabled="!formState?.id" type="primary" ghost @click="addRow()">
              新增一行
            </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const formState = ref({})
const loading = ref(false)
const dataSource = ref([])
const route = useRoute()
const router = useRouter()
const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row) => {
  row.distributionId = formState.value.id
  const { code, msg } = await post('war/equipmentConfig/doSaveEquipmentConfig', row)
  if (code !== 0) return message.error(msg || '操作失败')
  getDetailData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (item.equipmentNumber) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss') }
  dataSource.value.push(addRow)
}

const getMainData = async () => {
  const { data, code } = await post('/war/equipmentDistribution/getEquipmentDistributionList', {
    zjm: route.query?.id
  })
  if (code === 0) {
    formState.value = data[0]
  }
}
const getDetailData = async () => {
  loading.value = true
  const { data, code } = await post('/war/equipmentConfig/getEquipmentConfigList', {
    distributionId: route.query?.id
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
  }
}
const onDelete = async (row) => {
  if (row.isNew) {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  } else {
    const { code, msg } = await post('/war/equipmentConfig/doDelEquipmentConfig', { id: row.id })
    code === 0 ? getDetailData() : message.error(msg || '删除失败')
  }
}

watchEffect(() => {
  if (route && route.query?.id) {
    getMainData()
    getDetailData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-card-head) {
  padding-left: 8px;
}
</style>
<style>
.allot .ant-select-selection-search-input {
  margin-top: 7px !important;
}
</style>
